package dao

import (
	"fmt"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

// GetStaffUserList 获取员工列表
func (d *UserDao) GetStaffUserList(param *request.UserList) *dingo.ErrorWrap {

	var (
		lst    []users.UserInfoWithStaff
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.
		Table("users u").
		Select("u.*,r.name as role_name").
		Joins("left join roles r on u.role_id = r.id").
		Where("u.is_delete = ?", 0).
		Where("u.parent_id = ?", param.ParentId).
		Where("u.is_admin = ?", param.IsAdmin)

	if param.Name != "" {
		db.Where("u.name like ?", fmt.Sprint("%", param.Name, "%"))
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("u.%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("u.%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		db.Order("u.last_login_time desc, u.create_at desc")
	}

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)

}


// GetMaintainerListByParentId 获取员工列表By parent_id
func (d *UserDao) GetMaintainerListByParentId(parentId int) *dingo.ErrorWrap {
	var lst []*users.UserModel
	db := global.Orm.Debug().Table("users").
		Where("is_admin = 4 and is_delete = 0 and is_place = 0")

	db.Where("parent_id = ?", parentId)

	db.Order("id asc").Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// GetMaintainerListById 获取员工列表By id
func (d *UserDao) GetMaintainerListById(id int) *dingo.ErrorWrap {
	var lst []*users.UserModel
	db := global.Orm.Debug().Table("users").
		Where("is_admin = 4 and is_delete = 0 and is_place = 0")

	db.Where("id = ?", id)

	db.Order("id asc").Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}